<template>
  <div class="backend-test">
    <h1>后端连接测试</h1>
    
    <el-card class="test-card">
      <template #header>
        <div class="card-header">
          <span>API连接状态</span>
          <div class="test-buttons">
            <el-button @click="testHttpConnection" :loading="isHttpTesting">
              测试HTTP连接
            </el-button>
            <el-button @click="testHttpsConnection" :loading="isHttpsTesting">
              测试HTTPS连接
            </el-button>
            <el-button @click="testBackendConnection" :loading="isBackendTesting">
              测试后端连接
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="test-results">
        <div v-if="connectionStatus" class="status-item">
          <el-tag :type="connectionStatus.success ? 'success' : 'danger'">
            {{ connectionStatus.success ? '连接成功' : '连接失败' }}
          </el-tag>
          <p>{{ connectionStatus.message }}</p>
          <p v-if="connectionStatus.url">测试URL: {{ connectionStatus.url }}</p>
        </div>
        
        <div v-if="testResults" class="test-details">
          <h3>测试详情：</h3>
          <pre>{{ JSON.stringify(testResults, null, 2) }}</pre>
        </div>
      </div>
    </el-card>
    
    <el-card class="test-card">
      <template #header>
        <div class="card-header">
          <span>分诊功能测试</span>
          <div class="test-buttons">
            <el-button @click="testTriage" :loading="isTriageTesting">
              测试头痛患者
            </el-button>
            <el-button @click="testChestPain" :loading="isChestPainTesting">
              测试胸痛患者
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="triage-test">
        <el-form :model="testData" label-width="120px">
          <el-form-item label="主诉症状">
            <el-input 
              v-model="testData.chiefComplaint" 
              placeholder="请输入测试症状"
              type="textarea"
              :rows="3"
            />
          </el-form-item>
          
          <el-form-item label="症状列表">
            <el-input 
              v-model="testData.symptomsText" 
              placeholder="症状，用逗号分隔"
              type="textarea"
              :rows="2"
            />
          </el-form-item>
          
          <el-form-item label="收缩压/舒张压">
            <el-input v-model="testData.bloodPressure" placeholder="如: 120/80" />
          </el-form-item>
          
          <el-form-item label="心率">
            <el-input-number v-model="testData.heartRate" :min="0" :max="300" />
          </el-form-item>
          
          <el-form-item label="体温">
            <el-input-number v-model="testData.temperature" :min="30" :max="45" :precision="1" />
          </el-form-item>
          
          <el-form-item label="既往病史">
            <el-input 
              v-model="testData.medicalHistory" 
              placeholder="既往病史"
              type="textarea"
              :rows="2"
            />
          </el-form-item>
        </el-form>
        
        <div v-if="triageResult" class="triage-result">
          <h3>分诊结果：</h3>
          <div class="result-summary">
            <p><strong>推荐科室:</strong> {{ triageResult.recommendation.recommendedDepartment }}</p>
            <p><strong>优先级:</strong> {{ getPriorityText(triageResult.recommendation.priority) }}</p>
            <p><strong>置信度:</strong> {{ (triageResult.confidence * 100).toFixed(1) }}%</p>
          </div>
          <h4>详细结果：</h4>
          <pre>{{ JSON.stringify(triageResult, null, 2) }}</pre>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { MedicalRAGService, type TriageRequest } from '../services/medicalRAGService'
import axios from 'axios'

const isHttpTesting = ref(false)
const isHttpsTesting = ref(false)
const isBackendTesting = ref(false)
const isTriageTesting = ref(false)
const isChestPainTesting = ref(false)
const connectionStatus = ref<any>(null)
const testResults = ref<any>(null)
const triageResult = ref<any>(null)

const testData = reactive({
  chiefComplaint: '持续性头痛3天',
  symptomsText: '头痛,恶心,呕吐,发热',
  bloodPressure: '120/80',
  heartRate: 85,
  temperature: 38.5,
  medicalHistory: '无特殊病史'
})

// 测试HTTP连接
const testHttpConnection = async () => {
  isHttpTesting.value = true
  try {
    const response = await axios.get('http://localhost:56704/api/triage/test', {
      timeout: 5000
    })
    testResults.value = response.data
    connectionStatus.value = {
      success: true,
      message: 'HTTP连接成功',
      url: 'http://localhost:56704'
    }
    ElMessage.success('HTTP连接测试成功')
  } catch (error: any) {
    connectionStatus.value = {
      success: false,
      message: `HTTP连接失败: ${error.message}`,
      url: 'http://localhost:56704'
    }
    ElMessage.error('HTTP连接测试失败')
  } finally {
    isHttpTesting.value = false
  }
}

// 测试HTTPS连接
const testHttpsConnection = async () => {
  isHttpsTesting.value = true
  try {
    const response = await axios.get('https://localhost:56704/api/triage/test', {
      timeout: 5000
    })
    testResults.value = response.data
    connectionStatus.value = {
      success: true,
      message: 'HTTPS连接成功',
      url: 'https://localhost:56704'
    }
    ElMessage.success('HTTPS连接测试成功')
  } catch (error: any) {
    connectionStatus.value = {
      success: false,
      message: `HTTPS连接失败: ${error.message}`,
      url: 'https://localhost:56704'
    }
    ElMessage.error('HTTPS连接测试失败')
  } finally {
    isHttpsTesting.value = false
  }
}

// 测试后端连接
const testBackendConnection = async () => {
  isBackendTesting.value = true
  try {
    const result = await MedicalRAGService.testBackendConnection()
    connectionStatus.value = {
      success: result,
      message: result ? '后端连接成功' : '后端连接失败',
      url: '通过代理连接'
    }
    if (result) {
      ElMessage.success('后端连接测试成功')
    } else {
      ElMessage.error('后端连接测试失败')
    }
  } catch (error: any) {
    connectionStatus.value = {
      success: false,
      message: `后端连接失败: ${error.message}`,
      url: '通过代理连接'
    }
    ElMessage.error('后端连接测试失败')
  } finally {
    isBackendTesting.value = false
  }
}

// 测试头痛患者
const testTriage = async () => {
  isTriageTesting.value = true
  try {
    const requestData: TriageRequest = {
      chiefComplaint: '持续性头痛3天',
      symptoms: ['头痛', '恶心', '呕吐', '发热'],
      vitalSigns: {
        bloodPressure: '120/80',
        heartRate: 85,
        temperature: 38.5
      },
      medicalHistory: '无特殊病史',
      textData: '患者持续性头痛3天，伴有恶心呕吐和发热'
    }
    
    console.log('发送请求数据:', JSON.stringify(requestData, null, 2))
    
    const result = await MedicalRAGService.submitTriageRequest(requestData)
    triageResult.value = result
    
    // 验证结果合理性
    const department = result.recommendation.recommendedDepartment
    const reasoning = result.recommendation.reasoning
    
    if (department.includes('呼吸') && !reasoning.includes('头痛')) {
      ElMessage.warning('警告：推荐科室可能不正确，建议检查后端模型')
    } else {
      ElMessage.success('头痛患者分诊测试成功')
    }
  } catch (error: any) {
    ElMessage.error(`头痛患者分诊测试失败: ${error.message}`)
  } finally {
    isTriageTesting.value = false
  }
}

// 测试胸痛患者
const testChestPain = async () => {
  isChestPainTesting.value = true
  try {
    const requestData: TriageRequest = {
      chiefComplaint: '剧烈胸痛,伴有胸闷和呼吸困难',
      symptoms: ['胸痛', '胸闷', '呼吸困难', '心悸', '出汗', '恶心'],
      vitalSigns: {
        bloodPressure: '160/100',
        heartRate: 120,
        temperature: 37.2,
        respiratoryRate: 24,
        oxygenSaturation: 92
      },
      medicalHistory: '高血压病史5年,糖尿病病史3年',
      textData: '患者剧烈胸痛，伴有胸闷和呼吸困难'
    }
    
    console.log('发送胸痛患者请求数据:', JSON.stringify(requestData, null, 2))
    
    const result = await MedicalRAGService.submitTriageRequest(requestData)
    triageResult.value = result
    
    // 验证结果合理性
    const department = result.recommendation.recommendedDepartment
    const reasoning = result.recommendation.reasoning
    
    if (department.includes('心血管') || department.includes('心内科')) {
      ElMessage.success('胸痛患者分诊测试成功，推荐科室合理')
    } else {
      ElMessage.warning('警告：胸痛患者推荐科室可能不正确')
    }
  } catch (error: any) {
    ElMessage.error(`胸痛患者分诊测试失败: ${error.message}`)
  } finally {
    isChestPainTesting.value = false
  }
}

// 获取优先级文本
const getPriorityText = (priority: number): string => {
  const texts: Record<number, string> = {
    0: '急诊',
    1: '紧急',
    2: '常规',
    3: '非紧急'
  }
  return texts[priority] || '未知'
}
</script>

<style scoped>
.backend-test {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.test-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.test-buttons {
  display: flex;
  gap: 10px;
}

.status-item {
  margin-bottom: 15px;
}

.status-item p {
  margin: 10px 0;
  color: #606266;
}

.test-details, .triage-result {
  margin-top: 15px;
}

.test-details h3, .triage-result h3 {
  margin-bottom: 10px;
  color: #303133;
}

.result-summary {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 15px;
}

.result-summary p {
  margin: 5px 0;
  font-size: 14px;
}

pre {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  overflow-x: auto;
  font-size: 12px;
  line-height: 1.4;
}

.triage-test {
  margin-top: 15px;
}
</style> 